import axios from 'axios'
import { message, Modal } from 'ant-design-vue'
import { useUserStore } from '@/stores/user.ts'
import router from '@/router'

// 创建 Axios 实例
// 区分开发和生产环境
// const DEV_BASE_URL = "http://localhost:8080";
// const PROD_BASE_URL = "http://139.155.110.154";
const baseUrl = import.meta.env.VITE_APP_API_URL
// 如果不写这个 withCredentials 前端就不会携带 cookie ，会出现前端已经登录但是后端不认的情况
const instance = axios.create({
  baseURL: baseUrl,
  timeout: 10000,
  withCredentials: true,
})

// 全局请求拦截器
instance.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    // 设置token
    const userStore = useUserStore()
    if (userStore.getToken()) {
      config.headers.Token = `${userStore.getToken()}`
    }
    return config
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error)
  },
)

// 全局响应拦截器
instance.interceptors.response.use(
  function (response) {
    const { data } = response
    // 未登录
    if (data.code === 40100) {
      // 不是获取用户信息的请求，并且用户目前不是已经在用户登录页面，则跳转到登录页面
      if (
        !response.request.responseURL.includes('user/get/login') &&
        !window.location.pathname.includes('/user/login') &&
        !window.location.pathname.includes('/user/register')
      ) {
        Modal.confirm({
          title: '登录已过期',
          content: '请重新登录',
          onOk: () => {
            // 清除 token
            window.location.href = `/user/login?redirect=${router.currentRoute.value.fullPath}`
          },
          onCancel: () => {
            router.back()
          },
          type: 'warn',
        })
      }
    }
    if (data.code != 0) {
      message.error(data.message)
    }
    return response
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error)
  },
)

export default instance
